package org.example.login;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.*;
import java.security.MessageDigest;
import java.util.Properties;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");

        if ("register".equals(action)) {
            registerUser(request, response);
        } else if ("login".equals(action)) {
            loginUser(request, response);
        } else if ("logout".equals(action)) {
            logoutUser(request, response);
        }
    }

    private void registerUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            request.setAttribute("error", "用户名和密码不能为空");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        String encryptedPassword = md5Encrypt(password);
        User user = new User(username, encryptedPassword);

        HttpSession session = request.getSession();
        session.setAttribute("currentUser", username);


        writeToPropertiesFile(username, encryptedPassword);

        request.setAttribute("message", "注册成功，请登录");
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    private void loginUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String encryptedPassword = md5Encrypt(password);

        HttpSession session = request.getSession();
        User sessionUser = (User) session.getAttribute("user");

        boolean loginSuccess = false;

        if (sessionUser != null &&
                sessionUser.getUsername().equals(username) &&
                sessionUser.getPassword().equals(encryptedPassword)) {
            loginSuccess = true;
        } else if (checkUserInPropertiesFile(username, encryptedPassword)) {
            loginSuccess = true;
        }

        if (loginSuccess) {
            session.setAttribute("currentUser", username);
            response.sendRedirect("welcome.jsp");
        } else {
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    private void logoutUser(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        // 使用绝对路径重定向
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }


    private String md5Encrypt(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());

            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void writeToPropertiesFile(String username, String password) {
        String filePath = getServletContext().getRealPath("/WEB-INF/user.properties");

        Properties props = new Properties();
        File file = new File(filePath);
        if (file.exists()) {
            try (InputStream input = new FileInputStream(file)) {
                props.load(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try (OutputStream output = new FileOutputStream(file)) {
            props.setProperty(username, password);
            props.store(output, "User Information");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean checkUserInPropertiesFile(String username, String password) {
        String filePath = getServletContext().getRealPath("/WEB-INF/user.properties");
        Properties props = new Properties();

        try (InputStream input = new FileInputStream(filePath)) {
            props.load(input);
            String storedPassword = props.getProperty(username);
            return password.equals(storedPassword);
        } catch (IOException e) {
            return false;
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}